package org.example.common.aop;//package com.njwx.yq.common.aop;
//
//import org.example.common.ratelimiter.annotation.RateLimiter;
//import org.example.common.bean.CommonException;
//import lombok.extern.slf4j.Slf4j;
//import org.aspectj.lang.JoinPoint;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.annotation.Before;
//import org.aspectj.lang.annotation.Pointcut;
//import org.aspectj.lang.reflect.MethodSignature;
//import org.springframework.core.annotation.AnnotationUtils;
//import org.springframework.core.annotation.Order;
//import org.springframework.stereotype.Component;
//
//import java.lang.reflect.Method;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.concurrent.ConcurrentMap;
//
///**
// * <p>
// * 限流切面
// * </p>
// *
// * @author yangkai.shen
// * @since Created in 2019/9/12 14:27
// */
//@Slf4j
//@Aspect
//@Component
//@Order(2)
//public class RateLimiterAspect {
//    private static final ConcurrentMap<String, com.google.common.util.concurrent.RateLimiter> RATE_LIMITER_CACHE = new ConcurrentHashMap<>();
//
//    @Pointcut("@annotation(com.njwx.yq.common.ratelimiter.annotation.RateLimiter)")
//    public void rateLimit() {
//        // sonar
//    }
//
//    @Before("rateLimit()")
//    public void pointcut(JoinPoint point) {
//        MethodSignature signature = (MethodSignature) point.getSignature();
//        Method method = signature.getMethod();
//        // 通过 AnnotationUtils.findAnnotation 获取 RateLimiter 注解
//        RateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, RateLimiter.class);
//        if (rateLimiter != null && rateLimiter.qps() > RateLimiter.NOT_LIMITED) {
//            double qps = rateLimiter.qps();
//            String key = method.getName();
//            if (!RATE_LIMITER_CACHE.containsKey(key)) {
//                // 初始化 QPS
//                RATE_LIMITER_CACHE.put(key, com.google.common.util.concurrent.RateLimiter.create(qps));
//            }
//            if (log.isDebugEnabled()) {
//                log.debug("【{}】的QPS设置为: {}", key, RATE_LIMITER_CACHE.get(key).getRate());
//            }
//            // 尝试获取令牌
//            if (RATE_LIMITER_CACHE.get(key) != null && !RATE_LIMITER_CACHE.get(key).tryAcquire(rateLimiter.timeout(), rateLimiter.timeUnit())) {
//                throw new CommonException("请求频繁,请稍后再试.");
//            }
//        }
//    }
//}
